﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;

namespace PdfOrmGen
{
    public class PdfMapper
    {
        public static void CreateMapping(string pdfLocation, string className, string outputLocation)
        {
            if (!Directory.Exists(outputLocation))
            {
                Console.WriteLine(outputLocation + " : Directory doesn't exist");
                return;
            }

            if (!File.Exists(pdfLocation))
            {
                Console.WriteLine(pdfLocation + " : File does not exist");
                return;
            }

            PdfReader templatePDf = new PdfReader(pdfLocation);
            var buildInterface = new StringBuilder();
            var buildClass = new StringBuilder();

            var fields = templatePDf.AcroFields.Fields;

            if (!KeysAreInvalid(fields.Keys as List<string>))
                return;

            buildInterface.AppendLine("namespace Forms.Interfaces");
            buildInterface.AppendLine("{");
            buildInterface.AppendLine("    public interface I" + className);
            buildInterface.AppendLine("    {");

            buildClass.AppendLine("namespace Forms");
            buildClass.AppendLine("{");
            buildClass.AppendLine("    public class " + className);
            buildClass.AppendLine("    {");

            foreach (DictionaryEntry item in fields)
            {
                buildInterface.AppendLine("        string " + item.Key + "  { get; set; }");
                buildClass.AppendLine("        public string " + item.Key + " { get; set; }");
            }

            buildInterface.AppendLine("    }");
            buildInterface.AppendLine("}");
            buildClass.AppendLine("    }");
            buildClass.AppendLine("}");

            File.WriteAllText("I" + className + ".cs", buildInterface.ToString());
            File.WriteAllText(className + ".cs", buildClass.ToString());
        }

        private static bool KeysAreInvalid(List<string> list)
        {
            if (list == null)
                return false;
            if (list.Count == 0)
            {
                Console.WriteLine("No keys found.  Check your pdf");
                return false;
            }
            //need a better regex here
            var pattern = new Regex(@"(\w(\s)?)+");
            var result = list.Count(pattern.IsMatch);
            if (result > 0)
            {
                Console.WriteLine("This form contains keys are are not supported.");
                return false;
            }
            else return true;
        }
    }
}
